/*
 * @Author: silence
 * @Date: 2023-08-23 09:40:05
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-24 14:30:33
 * @Description: 配网控制器
 */

import 'dart:async';
import 'dart:io';

import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/permission/PermissionUtils.dart';
import 'package:ems_neutral_app/utils/router/ARouter.dart';
import 'package:ems_neutral_app/utils/toast/SilToastExtends.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wifi_iot/wifi_iot.dart';
import 'package:wifi_scan/wifi_scan.dart';

import '../../../utils/color/ColorUtils.dart';
import '../Interface/DeviceNetworkingInterface.dart';
import '../Interface/DeviceNetworkingInterfaceForSDER.dart';
import '../Interface/DeviceNetworkingInterfaceForYB.dart';
import '../Interface/DeviceNetworkingInterfaceForYZ.dart';
import '../Interface/WifiDeviceBackData.dart';

enum DNNetProgressItemState {
  /// 准备
  prepare,

  /// 进行中
  progressing,

  /// 成功
  success,

  /// 失败
  fail
}

class DeviceNetworkingController extends GetxController {
  /// 设备配网
  DeviceNetworkingInterface? _interface;

  /// 配网进度
  /// 1查找设备（查看当前链接的wifi是不是数采器wifi）
  Rx<DNNetProgressItemState> proByFindDevice =
      DNNetProgressItemState.prepare.obs;

  /// 2检查数采器设备的wifi链接状态（通过访问wifi后台是否能成功确认）
  Rx<DNNetProgressItemState> proByConnectState =
      DNNetProgressItemState.prepare.obs;

  /// 3给数采器配置家里的wifi网络（设备链接到云）
  Rx<DNNetProgressItemState> proBySetWifi = DNNetProgressItemState.prepare.obs;

  /// 4重启数采器设备（设备激活）
  Rx<DNNetProgressItemState> proByRestartDevice =
      DNNetProgressItemState.prepare.obs;

  // /// 5验证是否成功（获取数据）
  // Rx<DNNetProgressItemState> proByCheckSuccess =
  //     DNNetProgressItemState.prepare.obs;

  /// wifi名称
  String? ssid;

  /// wifi密码
  String? pwd;

  /// 初始化设备联网进度状态
  initDeviceNetProgressState() {
    this.proByFindDevice.value = DNNetProgressItemState.prepare;
    this.proByConnectState.value = DNNetProgressItemState.prepare;
    this.proBySetWifi.value = DNNetProgressItemState.prepare;
    this.proByRestartDevice.value = DNNetProgressItemState.prepare;
  }

  /// 开始设备配网
  Future<bool> beginDeviceNetworking(BuildContext context) async {
    /// 需要延迟
    await Future.delayed(Duration(microseconds: 350));

    // // 要绑定的wifi名称和密码不能为空
    if (SilTools.stringIsEmpty(this.ssid) || SilTools.stringIsEmpty(this.pwd)) {
      ARoute.pop(context);
      // // 要绑定的wifi名称和密码不能为空！
      SilToastExtends.toastMsg(
          LangOf(context)?.deviceNetworking?.noWifiNameAndPwd);
      return false;
    }
    WifiDeviceBackData? resultDeviceData;

    /// 1检查数采器设备的wifi链接状态（查看当前链接的wifi是不是数采器wifi）
    SilLog.d("1检查数采器设备的wifi链接状态（查看当前链接的wifi是不是数采器wifi）");

    /// 获取当前设备的ssid，初始化数采器，并获取数采器信息
    proByFindDevice.value = DNNetProgressItemState.progressing;

    /// 延迟伪装一下下
    await Future.delayed(Duration(seconds: 3));
    String? ssid = await this.getConnectedWifiSsid();
    DeviceNetworkingInterface? interface = this.setWifiDeviceInstance(ssid);
    if (interface == null) {
      /// '链接数采器wifi失败');
      proByFindDevice.value = DNNetProgressItemState.fail;
      return false;
    } else {
      proByFindDevice.value = DNNetProgressItemState.success;
    }

    /// 2检查数采器设备的wifi链接状态（通过访问wifi后台是否能成功确认）
    SilLog.d("2检查数采器设备的wifi链接状态（通过访问wifi后台是否能成功确认）");
    proByConnectState.value = DNNetProgressItemState.progressing;

    /// 延迟伪装一下下
    await Future.delayed(Duration(seconds: 2));
    resultDeviceData = await _interface?.checkDeiviceWifiConnectState();
    if (resultDeviceData?.data == '-1') {
      proByConnectState.value = DNNetProgressItemState.fail;
      return false;
    }
    proByConnectState.value = DNNetProgressItemState.success;

    /// 3给数采器配置家里的wifi网络（设备链接到云）
    SilLog.d("2给数采器配置家里的wifi网络（设备链接到云）");
    proBySetWifi.value = DNNetProgressItemState.progressing;
    // 延迟伪装一下下
    await Future.delayed(Duration(seconds: 3));
    resultDeviceData = await _interface?.deiviceSetHomeWifi(
        ssid: this.ssid ?? "", pwd: this.pwd ?? "");

    if (resultDeviceData?.data == '-1') {
      proBySetWifi.value = DNNetProgressItemState.fail;
      return false;
    }
    proBySetWifi.value = DNNetProgressItemState.success;

    /// 4重启数采器设备（设备激活）
    SilLog.d("3重启数采器设备（设备激活）");
    proByRestartDevice.value = DNNetProgressItemState.progressing;
    // 延迟伪装一下下
    await Future.delayed(Duration(seconds: 3));
    resultDeviceData = await _interface?.deiviceRestart();
    if (resultDeviceData?.data == '-1') {
      proByRestartDevice.value = DNNetProgressItemState.fail;
      return false;
    }
    proByRestartDevice.value = DNNetProgressItemState.success;

    /// 5验证是否成功（获取数据），重启之后设备要重启才生效，其实我们很难验证
    // SilLog.d("4验证是否成功（获取数据）");
    // proByCheckSuccess.value = DNNetProgressItemState.progressing;
    // resultDeviceData = await _interface?.checkIsSuccess();
    // if (resultDeviceData?.data == '-1') {
    //   ARoute.pop(context);
    //   proByCheckSuccess.value = DNNetProgressItemState.fail;
    //   return false;
    // }
    // proByCheckSuccess.value = DNNetProgressItemState.success;
    // ARoute.pop(context);
    return true;
  }

  /// 需要获取位置权限
  Future<bool> getLocation() async {
    bool locationEnabled;
    LocationPermission permission;

    locationEnabled = await Geolocator.isLocationServiceEnabled();
    if (!locationEnabled) {
      return false;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return false;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return false;
    }

    return locationEnabled;
  }

  /// 获取是否开启wifi
  Future<bool> isOpenedWifi() async {
    String? ip = await WiFiForIoTPlugin.getIP();
    return ip != null;
  }

  /// 检查wifi开关和定位权限
  Future<bool> checkWifiSwitchAndLocalPower(BuildContext context) async {
    bool isOpenWif = await this.isOpenedWifi();

    /// 1先检查wifi是否开启
    if (!isOpenWif) {
      SilAlertDialog.showAlertDialog(
          context,
          SilAlertDialogData(
              content: LangOf(context)
                  ?.deviceNetworking
                  ?.wifiNotEnabled, //手机Wi-Fi未开启，请打开手机Wi-Fi后，扫描附近的设备Wi-Fi
              confrimButtonTitle:
                  LangOf(context)?.deviceNetworking?.fine), //'好的'
          confrimFunc: () {});
      return false;
    } else {
      /// 2,定位权限
      bool isLocationEnabled = await this.getLocation();

      if (!isLocationEnabled) {
        PermissionUtils.permission_location();
        return false;
      }
      return isLocationEnabled;
    }
  }

  /// 获取已链接的wifi的名称（ssid），空表示未链接
  /// 需要获取位置权限
  Future<String?> getConnectedWifiSsid() async {
    String? ssid;
    bool isConnected = await WiFiForIoTPlugin.isConnected();
    if (isConnected) {
      ssid = await WiFiForIoTPlugin.getSSID();
    }
    return ssid;
  }

  /// 检查wifi是否是2.4Gwifi网络
  Future<bool> checkWifiGHZ() async {
    String? ip = await WiFiForIoTPlugin.getIP();
    bool isConnected = (ip != null); //await WiFiForIoTPlugin.isConnected();
    if (isConnected) {
      int frequency = await WiFiForIoTPlugin.getFrequency() ?? 0;
      SilLog.d("message::$frequency");

      if (frequency >= 2400 && frequency <= 2500) {
        print('WiFi为2.4GHz频段');
        return true;
      } else {
        /// 这里还有个合频（2.4G/5G）,要判断一下是不是合频wifi
        bool flag = await checkWifiMerge();
        return flag;
      }
    }
    return false;
  }

  /// 判断当前wifi是不是合频（2.4G/5G)
  /// 仅android有用，iOS获取不到wifi的频率
  Future<bool> checkWifiMerge() async {
    bool flag = false;
    String? ssid = await WiFiForIoTPlugin.getSSID();

    final can =
        await WiFiScan.instance.canGetScannedResults(askPermissions: true);

    if (can == CanGetScannedResults.yes) {
      List<WiFiAccessPoint> wifList =
          await WiFiScan.instance.getScannedResults();

      /// 判断当前的5G频率的WIFI，是不是同时也是2.4G频率的
      for (WiFiAccessPoint wifiPoint in wifList) {
        if (wifiPoint.ssid == ssid) {
          int frequency = wifiPoint.frequency;
          if (frequency >= 2400 && frequency <= 2500) {
            flag = true;
          }
        }
      }
    }
    return flag;
  }

  /// 设置当前的数采器实例
  DeviceNetworkingInterface? setWifiDeviceInstance(String? deviceSsid) {
    /// 设置当前数采器类型
    if (deviceSsid?.substring(0, 4) == "EAP-") {
      /// 思道尔
      _interface = DeviceNetworkingInterfaceForSDER();
    } else if (deviceSsid?.substring(0, 3) == "AP_") {
      /// 英臻
      _interface = DeviceNetworkingInterfaceForYZ();
    } else if (deviceSsid?.substring(0, 1) == "B" ||
        deviceSsid?.substring(0, 1) == "Q") {
      /// 益邦
      _interface = DeviceNetworkingInterfaceForYB();
    }
    return _interface;
  }

  /// 查询wifi列表
  /// 启动设备的系统设置页面：
  openWifiSettings() async {
    if (Platform.isIOS) {
      launch('App-Prefs:root=WIFI');
      return;
    }
    WiFiForIoTPlugin.setEnabled(true, shouldOpenSettings: true);
  }

  /// 获取数采器设备信息
  /// 从设备返回，获取数采器信息
  Future<WifiDeviceBackData> getWifiDeviceInfo(BuildContext context) async {
    String promptTextStr = "";
    SilAlertDialog.showLoadingDialog(context,
        indicatorColor: ColorUtils.color_theme,
        promptText: promptTextStr,
        promptTextStyle:
            TextStyle(color: ColorUtils.color_theme, fontSize: 14.sp));
    WifiDeviceBackData resultDeviceData =
        await _interface?.checkDeiviceWifiConnectState() ?? kFailDeviceData;
    ARoute.pop(context);
    return resultDeviceData;
  }
}
